package com.yps.io.aio.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class AsyncClientHandler implements CompletionHandler<Void, AsyncClientHandler>, Runnable {

	private String host;
	private int port;
	private AsynchronousSocketChannel channel;
	private CountDownLatch latch;
	public AsyncClientHandler(String host, int port) {
		this.host = host;
		this.port = port;
		try {
			//单例创建
			channel = AsynchronousSocketChannel.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		//创建CountDownLatch等待
		latch = new CountDownLatch(1);
		//发起异步连接操作，回调函数就是这个类的本身，如果连接成功会回调completed方法
		channel.connect(new InetSocketAddress(host, port),this,this);
		try {
			latch.await();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	//发送服务端成
	//意味着TCP三次握手成功
	@Override
	public void completed(Void result, AsyncClientHandler attachment) {
		System.out.println("客户端连接到服务器");
	}
	//连接服务端失败
	@Override
	public void failed(Throwable exc, AsyncClientHandler attachment) {
		System.out.println("连接服务器失败。。。");
		exc.printStackTrace();
		try {
			channel.close();
			latch.countDown();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendMsg(String msg) throws UnsupportedEncodingException {
		System.out.println(msg);
		byte[] req = msg.getBytes("UTF-8");
		ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
		writeBuffer.put(req);
		writeBuffer.flip();
		//异步写数据
		channel.write(writeBuffer, writeBuffer, new WriteHandler(channel, latch));
	}

}
